<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="园区/医院id" prop="deptId">
<!--        <el-form-item label="归属园区" prop="deptId" label-width="100px">-->
<!--          <el-tree-select v-model="form.deptId" :data="enabledDeptOptions"-->
<!--                          :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"-->
<!--                          placeholder="请选择归属园区" check-strictly/>-->
<!--        </el-form-item>-->
        <el-input
            v-model="queryParams.deptId"
            placeholder="请输入园区id"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="键名" prop="key">
        <el-input
            v-model="queryParams.key"
            placeholder="请输入键名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="值" prop="value">
        <el-input
            v-model="queryParams.value"
            placeholder="请输入值"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="配置说明" prop="desc">
        <el-input
            v-model="queryParams.desc"
            placeholder="请输入配置说明"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['health:config:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['health:config:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['health:config:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['health:config:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="configList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="园区" align="center" prop="deptId" width="100">
        <template #default="scope">
          <span>{{ getJobTypeLabel(scope.row.deptId, parks) }}</span>
<!--          <span>{{// scope.row.deptId,p}}</span>-->
        </template>
      </el-table-column>
      <el-table-column label="键名" align="center" prop="key" />
      <el-table-column label="值" align="center" prop="value" />
      <el-table-column label="配置说明" align="center" prop="desc" show-overflow-tooltip="true" width="250px" />
      <!-- 启用状态显示文本 -->
      <el-table-column label="启用状态" align="center" prop="usable">
        <template #default="scope">
          {{ scope.row.usable === 1 ? '启用' : '未启用' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['health:config:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['health:config:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改从业人员配置对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="configRef" :model="form" :rules="rules" label-width="80px">
<!--        <el-form-item label="所属地区" prop="deptId">-->
<!--          <el-select v-model="form.deptId" filterable placeholder="请选择">-->
<!--            <el-option-->
<!--                v-for="item in parks"-->
<!--                :key="item.value"-->
<!--                :label="item.label"-->
<!--                :value="item.value"-->
<!--            />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-col :span="12">
          <el-form-item label="归属园区" prop="deptId">
            <el-tree-select v-model="form.deptId" :data="enabledDeptOptions"
                            :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"
                            placeholder="请选择归属园区" check-strictly/>
          </el-form-item>
        </el-col>
        <el-form-item label="键名" prop="key">
          <el-input v-model="form.key" placeholder="请输入键名" />
        </el-form-item>
        <el-form-item label="值" prop="value">
          <el-input v-model="form.value" placeholder="请输入值" />
        </el-form-item>
        <el-form-item label="配置说明" prop="desc">
          <el-input v-model="form.desc" placeholder="请输入配置说明" />
        </el-form-item>
        <el-form-item label="启用状态" prop="usable">
          <el-select v-model="form.usable" placeholder="请选择启用状态">
            <el-option label="启用" :value="1"></el-option>
            <el-option label="未启用" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Config">
import {listConfig, getConfig, delConfig, addConfig, updateConfig} from "@/api/health/config"
import {getCurrentInstance} from 'vue'
import { loadParkId, parks} from "@/api/employee/applyBaseData.js";
import {deptTreeSelect} from "@/api/system/user.js";
import {useRoute} from "vue-router";
const {proxy} = getCurrentInstance()
import {ElMessageBox} from "element-plus";
const route=useRoute()
const configList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const enabledDeptOptions = ref(undefined)
const deptOptions = ref(undefined)
const noticeShown = ref(false)

function filterDisabledDept(deptList) {
  return deptList.filter(dept => {
    if (dept.disabled) {
      return false
    }
    if (dept.children && dept.children.length) {
      dept.children = filterDisabledDept(dept.children)
    }
    return true
  })
}
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptId: null,
    key: null,
    value: null,
    desc: null,
    usable: null
  },
  rules: {
    key: [
      {required: true, message: "键名不能为空", trigger: "blur"}
    ],
    usable: [
      {required: true, message: "启用状态不能为空", trigger: "change"}
    ]
  }
})

const {queryParams, form, rules} = toRefs(data)
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data
    enabledDeptOptions.value = filterDisabledDept(JSON.parse(JSON.stringify(response.data)))
  })
}
// 根据id获取标签名
function getJobTypeLabel(id, list) {
  let lableName = list.find(item => item.value == id);
  return lableName ? lableName.label : '未知';
}

// 检查并显示公告的函数
function checkAndShowNotice() {
  // 如果公告已经显示过，则不再显示
  if (noticeShown.value) return

  // 检查是否有键名为"isopen"且值为"true"的配置项
  const hasNotice = configList.value.some(item =>
      item.key === 'isopen' && item.value === 'true'
  )

  if (hasNotice) {
    openNotice()
    noticeShown.value = true // 标记公告已显示
  }
}
const parkMap = [
  { value: '100', label: '中川园区' },
  { value: '101', label: '西岔园区' },
  { value: '102', label: '秦川园区' }
]
/** 查询从业人员配置列表 */
function getList() {
  loading.value = true
  listConfig(queryParams.value).then(response => {
    configList.value = response.rows
    total.value = response.total
    loading.value = false
    checkAndShowNotice()

  })
}
const openNotice = () => {
  const title = '关于健康证办理的公告'
  const notice = '<p class="notice">尊敬的各位市民：</p>'
      + '<p class="notice">您好！感谢您一直以来对我们工作的支持与理解。近期，由于健康证新旧系统替换，给广大市民健康证办理工作带来了一定的影响。为确保大家能够顺利办理健康证，现将相关事宜公告如下：</p>'
      + '<p class="notice">一、自端午节假期前已申请但未能成功办理健康证的人员，请通过新系统进行预约。我们将根据预约情况，合理安排办理时间，确保大家能够尽快完成健康证的办理。</p>'
      + '<p class="notice">二、新系统登录地址：</p>'
      + '<p class="notice">1、个人申报页面链接</p>'
      + '<p style="color: #1c84c6">http://117.157.64.139:9000/employee/personApply</p>'
      + '<p class="notice">备注：无需登录，直接填写信息</p>'
      + '<p class="notice">2、企业申报页面</p>'
      + '<p style="color: #1c84c6">http://117.157.64.139:9000/employee/unitApply</p>'
      + '<p class="notice">备注：无需登录，直接填写信息</p>'
      + '<p class="notice">3、体检预约页面链接</p>'
      + '<p style="color: #1c84c6">http://117.157.64.139:9000/employee/reserve</p>'
      + '<p class="notice">备注：个人和企业（给员工预约）都在这里预约，如您遇到任何问题或困难，请及时与我们联系。我们将竭诚为您提供帮助，确保预约流程顺利进行。</p>'
      + '<p class="notice">三、给您带来的不便，我们深表歉意，也恳请各位市民予以谅解。我们将加快新系统的上线进度，尽快恢复正常的健康证办理工作，为大家提供更加便捷、高效的服务。</p>'
      + '<p class="notice">感谢您的理解与配合！</p>'

  ElMessageBox.alert(notice, title, {
    dangerouslyUseHTMLString: true,
    customClass: 'custom-notice',
    customStyle: {'max-width': '40%'}
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    deptId: null,
    key: null,
    value: null,
    desc: null,
    usable: null
  }
  proxy.resetForm("configRef")
}

/** 搜索框按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加从业人员配置"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getConfig(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改从业人员配置"
  })
}
watch(()=>route.fullPath,()=>{
//   重置查询参数
  Object.assign(queryParams.value, {
    pageNum: 1,
    pageSize: 10,
    deptId: null,
    key: null,
    value: null,
    desc: null,
    usable: null
  })
  getList()
},{immediate:true})
// onMounted(() => {
//   loadParkId()
//   getDeptTree()
//   getList()
//   // openNotice()
// })
onMounted( ()=>{
  // loadJobTypes()
   loadParkId()
  getDeptTree()
  getList()

})
/** 提交按钮 */
function submitForm() {
  proxy.$refs["configRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateConfig(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addConfig(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除从业人员配置编号为"' + _ids + '"的数据项？').then(function () {
    return delConfig(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('health/config/export', {
    ...queryParams.value
  }, `config_${new Date().getTime()}.xlsx`)
}
</script>
<style scoped>

</style>